/**
  @file
  @author Stefan Frings
*/

#include "netlistenerjob.h"

/** Search the configuration file */
QString searchConfigFile()
{
    QString binDir=QCoreApplication::applicationDirPath();
    QString appName=QCoreApplication::applicationName();
    QString fileName("config.ini");

    QStringList searchList;
    searchList.append(binDir);
    searchList.append(binDir+"/etc");
    searchList.append(binDir+"/../etc");
    searchList.append(binDir+"/../"+appName+"/etc");     // for development with shadow build (Linux)
    searchList.append(binDir+"/../../"+appName+"/etc");  // for development with shadow build (Windows)
    searchList.append(QDir::rootPath()+"etc/opt");
    searchList.append(QDir::rootPath()+"etc");
    searchList.append(":/misc/etc");

    foreach (QString dir, searchList)
    {
        QFile file(dir+"/"+fileName);
        if (file.exists())
        {
            fileName=QDir(file.fileName()).canonicalPath();
            qDebug("Using config file %s",qPrintable(fileName));
            return fileName;
        }
    }

    // not found
    foreach (QString dir, searchList)
    {
        qWarning("%s/%s not found",qPrintable(dir),qPrintable(fileName));
    }
    qFatal("Cannot find config file %s",qPrintable(fileName));
}

NetListenerJob::NetListenerJob(NetClientJob *clientJob, QObject *parent)
    : QObject(parent)
    , m_clientJob(clientJob)
    , m_templateCache(nullptr)
    , m_sessionStore(nullptr)
    , m_staticFileController(nullptr)
{
     // Find the configuration file
     QString configFileName=searchConfigFile();


     // Configure template loader and cache
     QSettings* templateSettings=new QSettings(configFileName,QSettings::IniFormat, this);
     templateSettings->beginGroup("templates");
     m_templateCache=new TemplateCache(templateSettings, this);

     // Configure session store
     QSettings* sessionSettings=new QSettings(configFileName,QSettings::IniFormat, this);
     sessionSettings->beginGroup("sessions");
     m_sessionStore=new HttpSessionStore(sessionSettings, this);

     // Configure static file controller
     QSettings* fileSettings=new QSettings(configFileName,QSettings::IniFormat, this);
     fileSettings->beginGroup("docroot");
     m_staticFileController=new StaticFileController(fileSettings, this);

     // Configure and start the TCP listener
     QSettings* listenerSettings=new QSettings(configFileName,QSettings::IniFormat, this);
     listenerSettings->beginGroup("listener");
     new HttpListener(listenerSettings, new NetListenerRequestHander(m_clientJob, this), this);
}

NetListenerJob::~NetListenerJob()
{

}
